<?php

namespace app\controllers;

use yii\helpers\ArrayHelper;
use Yii;
use app\models\User;
use app\models\AccPayAddress;
use app\models\PaymentType;
use app\models\UserSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * UserController implements the CRUD actions for User model.
 */
class UserController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all User models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new UserSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->getQueryParams());

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single User model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new User model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new User();
		$model->setScenario('create');		
		$modelAccPayAddress = new AccPayAddress();
		
        if ($model->load(Yii::$app->request->post())) {
		//nếu là khách thì luôn luôn tạo mới là người dùng thường
			if(Yii::$app->user->isGuest)
			{
				$model->acc_type = 1;
			}
			$model->password = md5($model->password);
			$model->password_confirm = $model->password;
			$model->save();
			$modelAccPayAddress->load(Yii::$app->request->post());
			$modelAccPayAddress->acc_id = $model->acc_id;
			$modelAccPayAddress->save();
			if(Yii::$app->user->isGuest)
			{
				return $this->goHome();
			}
			else
			{
				return $this->redirect(['view', 'id' => $model->acc_id]);
			}
        } else {
            return $this->render('create', [
                'model' => $model,
				'modelAccPayAddress' => $modelAccPayAddress,
				'arrayPaymentType' => PaymentTypeController::getPaymentType(),
            ]);
        }
    }

    /**
     * Updates an existing User model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
		$model->setScenario('update');		
		$username = $model->username;
		$old_password = $model->password;
		
	//có thay đổi mật khẩu hay không?
		$flagPassChanged = false;
		
		$modelAccPayAddress = $model->getAccPayAddresses()->one();

        if ($model->load(Yii::$app->request->post()) && $modelAccPayAddress->load(Yii::$app->request->post())) {
		//không được thay đổi username
			$model->username = $username;
		//mật khẩu như cũ là không thay đổi
			if($model->password==$old_password)
			{
				$model->password = $old_password;
				$model->password_confirm = $old_password;
			}
			else
			{
				$model->password = md5($model->password);
				$model->password_confirm = $model->password;
				$flagPassChanged = true;
			}	
			if ($model->validate()) {
				$model->save();
				$modelAccPayAddress->save();
			//nếu tự thay đổi mật khẩu thì phải đăng nhập lại
				if(Yii::$app->user->identity->acc_id==$id && $flagPassChanged){					
					Yii::$app->user->logout();
					return $this->goHome();
				}
				return $this->redirect(Yii::$app->user->identity->acc_id!=$id?['view', 'id' => $id]:['update', 'id' => $id]);
			} else {
				return $this->render('update', [
					'model' => $model,
					'modelAccPayAddress' => $modelAccPayAddress,
					'arrayPaymentType' => PaymentTypeController::getPaymentType(),
				]);
			}
        } else {
            return $this->render('update', [
                'model' => $model,
				'modelAccPayAddress' => $modelAccPayAddress,
				'arrayPaymentType' => PaymentTypeController::getPaymentType(),
            ]);
        }
    }

    /**
     * Deletes an existing User model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }
	
    /**
     * Cấp mới mật khẩu
     */
    public function actionReset()
    {
		$model = new User();
		
        if($model->load(Yii::$app->request->post()))
		{
			$email = $model->email;
			$model = $this->findModelByEmail($email);
		//nếu email có trong hệ thống
			if($model!=null){
			//tạo mật khẩu mới ngẫu nhiên
				$password = md5(rand(54,7986));
			//gửi mail mật khẩu mới cho người dùng
				Yii::$app->mail->compose()
					 ->setFrom('hotro@thongtinmientay.vn')
					 ->setTo($email)
					 ->setSubject('[CAPTCHA TTMT] Thông báo')
					 ->setHtmlBody('<b>Chào thành viên,</b><br/>
					 Đây là mật khẩu mới của bạn: '.$password.'<br/>
					 Vui lòng đăng nhập và thay đổi mật khẩu <a href='.
					 Yii::$app->UrlManager->createAbsoluteUrl('/site/login').'>tại đây.</a><br/>
					 Trân trọng!')
					 ->send();
			//lưu mật khẩu mới
				$model->password = md5($password);
				if($model->save()){
					$this->goHome();
				}
				else
				{
					return $this->render('reset', [
						'model' => $model,
					]);					
				}
			}
			else
			{
		//ngược lại thì trở về trang reset mật khẩu
				$model = new User();
				$model->email = $email;
				$model->addError('email','Email không tồn tại trong hệ thống');
				return $this->render('reset', [
					'model' => $model,
				]);
			}
		}
		return $this->render('reset', [
			'model' => $model,
		]);
    }

    /**
     * Finds the User model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return User the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = User::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
	
	

    /**
     * Finds the User model based on its username value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $username
     * @return User the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModelByAccName($username)
    {
        if (($model = User::find()->where(['username' => $username])->one()) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
	/**
     * Finds the User model based on its email value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $email
     * @return User the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModelByEmail($email)
    {
        if (($model = User::find()->where(['email' => $email])->one()) !== null) {
            return $model;
        } else {
            return null;
        }
    }
	
	//lấy danh sách địa chỉ email của quản trị viên
	public static function getAdminEmail()
    {
		$model = new User();
        $arrayEmail = ArrayHelper::map($model->findBySql('SELECT full_name, email FROM user WHERE acc_type = 0')->asArray()->all(), 'email', 'full_name');

        return $arrayEmail;
    }
}
